package org.ifilm.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.ifilm.model.Message;
import org.ifilm.model.MessageSubject;
import org.springframework.stereotype.Repository;

/**
 * 
 * @author Mustafa Genç
 *
 */
@Repository
public class MessageDaoImpl implements MessageDao {
	@PersistenceContext
	private EntityManager entityManager;

	@Override
	public Message createMessage(Message message) {
		return entityManager.merge(message);
	}
	
	@Override
	public MessageSubject createMessageSubject(MessageSubject messageSubject) {
		return entityManager.merge(messageSubject);
	}

	@Override
	public List<MessageSubject> getMessageSubjects(Long userId) {
		try {
			Query query = entityManager.createQuery(getMessagesQuery());
			query.setParameter("receiver", userId);
			query.setParameter("sender", userId);
			
			return (List<MessageSubject>)query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private String getMessagesQuery() {
		StringBuilder strBuild = new StringBuilder();
		strBuild.append("select m from messagesubject m where m.receiver.id=:receiver or m.sender.id=:sender order by m.creationTime DESC");
		return strBuild.toString();
	}

	@Override
	public MessageSubject getMessageSubject(Long messageSubjectId) {
		try {
			Query query = entityManager.createQuery(getMessageSubjectQuery());
			query.setParameter("id", messageSubjectId);
			
			return (MessageSubject)query.getSingleResult();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private String getMessageSubjectQuery() {
		StringBuilder strBuild = new StringBuilder();
		strBuild.append("select m from messagesubject m where m.id=:id order by m.updateTime DESC");
		return strBuild.toString();
	}

	@Override
	public List<MessageSubject> getUnreadMessages(Long userId) {
		try {
			Query query = entityManager.createQuery(getUnreadMessageCountQuery());
			query.setParameter("userId", userId);
			
			return (List<MessageSubject>)query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private String getUnreadMessageCountQuery() {
		StringBuilder strBuild = new StringBuilder();
		strBuild.append("select m from messagesubject m where m.lastReceiverId=:userId and hasUnread=1 order by m.updateTime DESC");
		return strBuild.toString();
	}
}